package com.wowangz.cms.dailyoperation.storeuser.api;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.wowangz.cms.common.pojo.AjaxDataEntity;
import com.wowangz.cms.common.utils.CommonCrypto;
import com.wowangz.cms.common.utils.DataFormat;
import com.wowangz.cms.common.utils.SysConstant;
import com.wowangz.cms.component.datagrid.pojo.DataGrid;
import com.wowangz.cms.component.datagrid.pojo.DataResult;
import com.wowangz.cms.component.datagrid.pojo.DataStyle;
import com.wowangz.cms.component.datagrid.pojo.PangingParam;
import com.wowangz.cms.component.datagrid.utils.DataTypeConstant;
import com.wowangz.cms.component.datagrid.utils.PangingTools;
import com.wowangz.cms.dailyoperation.store.pojo.AdminUser;
import com.wowangz.cms.dailyoperation.store.pojo.StoreEntity;
import com.wowangz.cms.dailyoperation.store.service.StoreService;
import com.wowangz.cms.dailyoperation.storeuser.service.AdminUserService;
import com.wowangz.cms.syscore.IssTransactionContainer;
import com.wowangz.cms.syscore.api.BaseController;
import com.wowangz.cms.syscore.api.JSONFactory;
import com.wowangz.cms.syscore.utils.MessageResourcesUtils;
import com.wowangz.cms.syscore.utils.ServletUtils;
import com.wowangz.cms.systemmanage.channel.api.ChannelController;

@SuppressWarnings("unchecked")
@Scope("prototype")
@Controller
public class StoreUserController extends BaseController {
	
	private static Logger logger = LoggerFactory.getLogger(StoreUserController.class);

	/**
	 * 新增商户用户信息
	 *
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/dailyoperation/storeuser/addAdminUser.web", method = { RequestMethod.GET, RequestMethod.POST })
	public String addAdminUser(HttpServletRequest request, HttpServletResponse response, Model model) {
		AdminUser adminUser = null;
		try {
			adminUser = (AdminUser) ServletUtils.getParametersToBaseEntity(request, AdminUser.class);
			adminUser.setInputtime(new Date());
			adminUser.setInputuserid(userContext.getLoginUser().getId());
			adminUser.setModifytime(new Date());
			String loginname = adminUser.getLoginname() + "@" + request.getParameter("website");
			adminUser.setModifyuserid(userContext.getLoginUser().getId());
			adminUser.setLoginname(loginname);
			adminUser.setStatusid(SysConstant.RecordStatus.VALID);
			String passwordSHA = CommonCrypto.encryptSHAEncoder("123456");
			adminUser.setPassword(passwordSHA);
			AdminUserService adminUserService = (AdminUserService) IssTransactionContainer.getInstance(AdminUserService.class, true);

			adminUserService.add(adminUser);
			logger.info("新增商户[{}]用户[{}]信息成功", adminUser.getStoreid(),adminUser.getId());
			userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert1"));
			userContext.setCloseWindow(true);
		} catch (Exception e) {
			logger.error("新增商户[{}]用户[{}]信息失败", adminUser.getStoreid(),adminUser.getId(),e);
			e.printStackTrace();
			userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert2"));
		}
		return "/WEB-INF/jsp/dailyoperation/storeuser/storeUserAdd";
	}

	/**
	 * 删除商户用户信息
	 *
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "/dailyoperation/storeuser/deleteAdminUser.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void deleteAdminUser(HttpServletRequest request, HttpServletResponse response, Model model) {
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		try {
			Long userId = Long.valueOf(getRequest().getParameter("id"));
			AdminUser adminUser = new AdminUser();
			adminUser.setId(userId);
			adminUser.setStatusid(SysConstant.RecordStatus.INVALID);
			AdminUserService adminUserService = (AdminUserService) IssTransactionContainer.getInstance(AdminUserService.class, false);
			adminUserService.delete(adminUser);
			userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert3"));
			response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, userContext));
		} catch (Exception e) {
			e.printStackTrace();
			userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert4"));
		}
	}

	/**
	 * 打开“商户用户信息管理”列表加载列表数据
	 *
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "/dailyoperation/storeuser/queryAdminUserListInfoDataGrid.json")
	public void queryAdminUserListInfoDataGrid(HttpServletRequest request, HttpServletResponse response, Model model) {

		PangingParam pangingParam = null;
		DataResult dataResult = new DataResult();
		DataGrid dataGrid = null;

		try {
			pangingParam = (PangingParam) ServletUtils.getParametersToBaseEntity(request, PangingParam.class);
			HashMap<String, Object> map = ServletUtils.getParametersToHashMap(request);
			dataGrid = new DataGrid();
			dataGrid.setPangingParam(pangingParam);

			map.put("startrow", dataGrid.getStartrow());
			map.put("endrow", dataGrid.getEndrow());
			map.put("rows", dataGrid.getRows());
			map.put("sort", dataGrid.getSort());
			map.put("order", dataGrid.getOrder());
			map.put("statusid", SysConstant.RecordStatus.VALID);

			AdminUserService adminUserService = (AdminUserService) IssTransactionContainer.getInstance(AdminUserService.class, false);
			long resultCount = adminUserService.findResultCount(map);
			List<AdminUser> resultList = adminUserService.findResultList(map);

			DataStyle dataStyle = new DataStyle();
			dataStyle.setPageIndex(pangingParam.getPage());
			dataStyle.setDataCount(resultCount);
			dataStyle.setDataList(resultList);
			dataStyle.addDepict("modifytime", DataTypeConstant.DATETIME);
			dataStyle.addDepict("id", DataTypeConstant.LONG);
			dataStyle.addDepict("number", DataTypeConstant.STRING);
			dataStyle.addDepict("email", DataTypeConstant.STRING);
			dataStyle.addDepict("name", DataTypeConstant.STRING);
			dataStyle.addDepict("loginname", DataTypeConstant.STRING);
			dataResult = PangingTools.buildResultPagerInfo(dataStyle);

			if (pangingParam.getReportExportType() == 0) {
				response.getWriter().write(JSONFactory.toJSONString(dataResult, userContext));
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 点击菜单"商户用户信息管理"显示“商户用户信息管理”列表
	 *
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/dailyoperation/storeuser/manageList.web")
	public String queryProvinceList(HttpServletRequest request, HttpServletResponse response, Model model) {

		return "/WEB-INF/jsp/dailyoperation/storeuser/storeUserList";
	}

	/**
	 * 跳转商户用户信息添加页面
	 *
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/dailyoperation/storeuser/toAddAdminUser.web")
	public String toAddAdminUser(HttpServletRequest request, HttpServletResponse response, Model model) {
		return "/WEB-INF/jsp/dailyoperation/storeuser/storeUserAdd";
	}

	/**
	 * 跳转修改商户用户信息页面
	 *
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/dailyoperation/storeuser/toUpdateAdminUser.web")
	public String toUpdateCity(HttpServletRequest request, HttpServletResponse response, Model model) {
		try {
			String userId = getRequest().getParameter("id");
			AdminUserService adminUserService = (AdminUserService) IssTransactionContainer.getInstance(AdminUserService.class, false);
			AdminUser adminUser = adminUserService.findAdminUserById(userId);
			StoreService storeService = (StoreService) IssTransactionContainer.getInstance(StoreService.class, false);
			StoreEntity store = storeService.findOne(adminUser.getStoreid());
			model.addAttribute("adminUser", adminUser);
			model.addAttribute("store", store);
			model.addAttribute("validstart", DataFormat.formatDate(adminUser.getValidstart(), DataFormat.DT_YYYY_MM_DD));
			model.addAttribute("validend", DataFormat.formatDate(adminUser.getValidend(), DataFormat.DT_YYYY_MM_DD));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/WEB-INF/jsp/dailyoperation/storeuser/storeUserUpdate";
	}

	/**
	 * 修改商户用户信息
	 *
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/dailyoperation/storeuser/updateAdminUser.web", method = { RequestMethod.GET, RequestMethod.POST })
	public String updateCountry(HttpServletRequest request, HttpServletResponse response, Model model) {
		AdminUser adminUser = null;
		try {
			adminUser = (AdminUser) ServletUtils.getParametersToBaseEntity(request, AdminUser.class);
			adminUser.setModifytime(new Date());
			AdminUserService adminUserService = (AdminUserService) IssTransactionContainer.getInstance(AdminUserService.class, true);
			adminUserService.update(adminUser);
			userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert6"));
			userContext.setCloseWindow(true);
		} catch (Exception e) {
			e.printStackTrace();
			userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert7"));
		}
		return "/WEB-INF/jsp/dailyoperation/storeuser/storeUserUpdate";
	}

	@RequestMapping(value = "/dailyoperation/storeuser/validattionAdminUser.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void validattionAdminUser(HttpServletRequest request, HttpServletResponse response, Model model) {
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		try {
			AdminUser adminUser = null;
			StringBuffer errorMsg = new StringBuffer();
			HashMap<String, Object> map = new HashMap<String, Object>();
			adminUser = (AdminUser) ServletUtils.getParametersToBaseEntity(request, AdminUser.class);

			AdminUserService adminUserService = (AdminUserService) IssTransactionContainer.getInstance(AdminUserService.class, false);
			map.put("statusid", SysConstant.RecordStatus.VALID);
			if (null != adminUser.getId()) {
				map.put("id", adminUser.getId());
			}
			map.put("loginname", adminUser.getLoginname());
			if (!adminUserService.validationAdminUser(map)) {
				errorMsg.append(MessageResourcesUtils.getMessage(request, "systemmanage.User.check.loginname"));
			}
			map.remove("loginname");

			if (StringUtils.isNotEmpty(errorMsg.toString())) {
				userContext.setErrorMessage(errorMsg.toString());
			}
			response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, userContext));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
